const http = require("http");
const fs = require("fs");
http.createServer((request, response) => {
    console.log('request');

    const {
      url,
      method,
      headers
    } = request;
    if (url === "/" && method === 'GET') {
      fs.readFile('index1.html', (err, data) => {
        if (err) {
          setResponseUtil(response, 500, 'text/plain;charset=utf-8', '500 服务器挂了')
          return
        }
        setResponseUtil(response, 200, 'text/html', data);
      })
    } else if (url === '/users' && method === 'GET') {
      setResponseUtil(response, 200, 'application/json', JSON.stringify({
        'name': 'meng'
      }));
    } else if (method === 'GET' && headers.accept.indexOf('image/*')) {
      // 流的操作
      fs.createReadStream('.' + url).pipe(response);
    } else {
      setResponseUtil(response, 404, 'text/plain;charset=utf-8', '服务端没找到');
    }
  })
  .listen(3000, () => {
    console.log("http://localhost:3000");
  })


function setResponseUtil(response, statusCode, contentType, data) {
  response.statusCode = statusCode;
  response.setHeader('Content-type', contentType);
  response.end(data);
}